package com.xjcs.saplingplan.room.utils

import androidx.annotation.WorkerThread
import com.nlf.calendar.Lunar
import com.nlf.calendar.Solar
import com.xjcs.saplingplan.MainApp
import com.xjcs.saplingplan.room.AppDatabase
import com.xjcs.saplingplan.room.bean.countdown.CountdownBean

object CountdownRoomUtils {

    private val countdownDao by lazy {
        AppDatabase.getInstance(MainApp.getAppContext()).countdownDao()
    }

    @WorkerThread
    fun insert(bean: CountdownBean){
        countdownDao.insert(bean)
    }

    @WorkerThread
    fun insertList(beanList: MutableList<CountdownBean>){
        countdownDao.insertList(beanList)
    }

    @WorkerThread
    fun getAllCountdownList(userId: String, countdownCateName: String): MutableList<CountdownBean>{
        val countdownList = if(countdownCateName.isEmpty()) {
            countdownDao.getAllCountdownList(userId)
        }else{
            countdownDao.getAllCountdownListByCate(userId, countdownCateName)
        }
        val passedList = mutableListOf<CountdownBean>()
        val noPassedList = mutableListOf<CountdownBean>()
        val resultList = mutableListOf<CountdownBean>()
        if(countdownList.size > 0){
            val todaySolar = Solar()
            val todayLunar = Lunar(Solar(todaySolar.year, todaySolar.month, todaySolar.day))
            countdownList.forEach { bean ->
                val target = bean.getTargetDateStr(todaySolar, todayLunar)
                bean.targetDateStr = target.first
                bean.targetDay = target.second
                if(bean.targetDay >= 0){
                    noPassedList.add(bean)
                }else{
                    passedList.add(bean)
                }
            }
            //倒数日列表排序
            noPassedList.sortBy { it.targetDay }
            passedList.sortByDescending { it.targetDay }
            resultList.addAll(noPassedList)
            resultList.addAll(passedList)
        }
        return resultList
    }

}